<template>
  <!--选择图片-->
  <div class="ui-picture">
    <el-checkbox-group v-model="imgList">
    <div class="ui-tags ui-image-tabs">
      <el-tabs v-model="activeName" @tab-click="handleTagsClick">
        <el-tab-pane label="商家图片" name="ONGOING">
          <div class="ui-picture-content">
            <div class="ui-picture-left">
              <!--<div class="ui-picture-search">
                <el-input
                  placeholder="请输入分组名称"
                  v-model="groupName">
                  <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer;"></i>
                </el-input>
              </div>-->
              <div class="ui-picture-type">
                <el-scrollbar style="height:100%;">
                  <div @click="changeType(index)" v-for="(item,index) of allImageGroup" class="ui-group-item" :class="{'ui-choose-item':index === typeIndex}">{{item.groupName}}<span v-if="index === typeIndex" style="margin-left:10px;">({{tableData.page.Allpage === undefined ? 0 : tableData.page.Allpage}})</span></div>
                </el-scrollbar>
              </div>
            </div>
            <div class="ui-picture-right">
              <div class="ui-search">
                <div class="ui-search-display">
                  <el-button @click="openImgDialog" type="primary" style="width:80px;height:30px;padding:0;font-size: 13px;"><i class="fa fa-plus" style="margin-right:5px;"></i>上传图片</el-button>
                </div>
                <div class="ui-search-input">
                  <el-input placeholder="请输入图片名称" v-model="searchModel.name">
                    <el-button slot="append" @click="search()">查询</el-button>
                  </el-input>
                </div>
              </div>
              <div class="ui-pic-list">
                <el-scrollbar style="height:100%;">
                  <div class="ui-pic-item-list">
                    <div class="ui-pic-item-list-item" v-for="(item,index) of tableData.data" @click="chooseOneImg(item.url)">
                      <div class="ui-pic-item-list-img" :style="{'background-image':'url('+item.url+')'}"></div>
                      <!--<div class="ui-pic-item-list-text">{{item.fileName}}</div>
                      <div class="ui-select-mask" v-if="picId === item.id">
                        <img src="../../assets/basic/pictureChoose.png">
                      </div>-->
                      <div class="ui-pic-item-list-text"><el-checkbox :label="item.url"  @click.stop.native="">{{''}}</el-checkbox>{{item.fileName}}</div>
                      <div class="ui-pic-item-list-size">
                        <div class="ui-pic-item-list-size-filesize">{{item.fileSize}}</div>
                        <div class="ui-pic-item-list-size-date">{{item.createTime.split(" ")[0]}}上传</div>
                      </div>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
              <div class="ui-pic-bottom">
                <!--<el-button @click="openImgDialog" type="primary" style="width:80px;height:30px;padding:0;font-size: 13px;"><i class="fa fa-plus" style="margin-right:5px;"></i>上传图片</el-button>-->
                <div class="ui-pagination">
                  <el-pagination background v-on:size-change="tableData.page.handleSizeChange" v-on:current-change="tableData.page.handleCurrentChange" v-bind:current-page="tableData.page.CurrentPage?tableData.page.currentPage:1"  v-bind:page-size="tableData.page.pagesize" layout="total,prev, pager, next" v-bind:total="tableData.page.Allpage"  v-if="tableData.isPage">
                  </el-pagination>
                </div>
              </div>
              <div class="ui-picture-bottom">
                <div class="ui-choose-button">
                  <el-button type="primary" class="ui-button" @click="confirmImg">确定</el-button>
                  <el-button class="ui-button" @click="cancleImg">取消</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="系统图片" name="UNSTART">
          <div class="ui-picture-content">
            <div class="ui-picture-left">
              <div class="ui-picture-type">
                <el-scrollbar style="height:100%;">
                  <div @click="changeType2(index)" v-for="(item,index) of allSystemImageGroup" class="ui-group-item" :class="{'ui-choose-item':index === typeIndex2}">{{item.groupName}}<span v-if="index === typeIndex2" style="margin-left:10px;">({{tableData2.page.Allpage === undefined ? 0 : tableData2.page.Allpage}})</span></div>
                </el-scrollbar>
              </div>
            </div>
            <div class="ui-picture-right">
              <div class="ui-search">
                <div class="ui-search-display">
                </div>
                <div class="ui-search-input">
                  <el-input placeholder="请输入图片名称" v-model="searchModel2.name">
                    <el-button slot="append" @click="search2()">查询</el-button>
                  </el-input>
                </div>
              </div>
              <div class="ui-pic-list">
                <el-scrollbar style="height:100%;">
                  <div class="ui-pic-item-list">
                    <div class="ui-pic-item-list-item" v-for="(item,index) of tableData2.data" @click="chooseOneImg(item.url)">
                      <div class="ui-pic-item-list-img" :style="{'background-image':'url('+item.url+')'}"></div>
                      <div class="ui-pic-item-list-text"><el-checkbox :label="item.url" @click.stop.native="">{{''}}</el-checkbox>{{item.fileName}}</div>
                      <div class="ui-pic-item-list-size">
                        <div class="ui-pic-item-list-size-filesize">{{item.fileSize}}</div>
                        <div class="ui-pic-item-list-size-date">{{item.createTime.split(" ")[0]}}上传</div>
                      </div>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
              <div class="ui-pic-bottom">
                <!--<el-button @click="openImgDialog" type="primary" style="width:80px;height:30px;padding:0;font-size: 13px;"><i class="fa fa-plus" style="margin-right:5px;"></i>上传图片</el-button>-->
                <div class="ui-pagination">
                  <el-pagination background v-on:size-change="tableData2.page.handleSizeChange" v-on:current-change="tableData2.page.handleCurrentChange" v-bind:current-page="tableData2.page.CurrentPage?tableData2.page.currentPage:1"  v-bind:page-size="tableData2.page.pagesize" layout="total,prev, pager, next" v-bind:total="tableData2.page.Allpage"  v-if="tableData2.isPage">
                  </el-pagination>
                </div>
              </div>
              <div class="ui-picture-bottom">
                <div class="ui-choose-button">
                  <el-button type="primary" class="ui-button" @click="confirmImg">确定</el-button>
                  <el-button class="ui-button" @click="cancleImg">取消</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    </el-checkbox-group>
    <!--上传图片-->
    <div v-if="uploadImageVisible">
      <el-dialog
        title="上传图片"
        :visible.sync="uploadImageVisible"
        :modal-append-to-body="false"
        width="590px"
        height="300px">
        <div style="padding:30px 20px;box-sizing: border-box;">
          <upload-image @refresh="refreshImg" @close="closeDialog"></upload-image>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
  import {uploadImage,queryConditionList,queryAllImageGroup,querySystemConditionList,queryAllSystemGroup} from '@/api/image'
  import { alertSuccess,alertError,alertWarning,formatTime } from '@/utils/index'
  import UploadImage from '@/components/DIY/uploadImage'
  export default {
    props:['choosedImg'],
    components: {
      UploadImage
    },
    data(){
      return {
        imgList:[],
        fileList:[],
        allImageGroup:[],
        uploadImageVisible:false,
        url:require('../../assets/basic/timg111.jpg'),
        typeIndex:0,
        activeName:'ONGOING',
        chooseImage:'',
        groupName:'',
        picName:'',
        picId:'',
        imgIndex:0,
        typeList:[
          {
            groupName:'全部分组',
            id:'-1'
          },
          {
            groupName:'未分组',
            id:'0'
          },
        ],
        tableData: {
          data: [],
          isPage: false,
          multipleSelection: [],
          page:{}
        },
        searchModel: {
          groupId:'',
          isFull:1,
          name:'',
          pageNum:1,
          pageSize:12,
          countSql:true,
          reasonable:true,
        },
        pageOptions: {
          currentChageFlag: false,
        },
        searchModel2: {
          groupId:'',
          isFull:1,
          name:'',
          pageNum:1,
          pageSize:12,
          countSql:true,
          reasonable:true,
        },
        tableData2: {
          data: [],
          isPage: false,
          multipleSelection: [],
          page:{}
        },
        typeIndex2:0,
        allSystemImageGroup:[],
      }
    },
    methods: {
      // *********************************** 公共方法 *****************************************
      filterNullFields (options) { // 删除空字段
        let param = Object.assign(options)
        if (Object.keys.length > 0) {
          for (let key in param) {
            if (!param[key] && param[key] !== 0) {
              delete param[key]
            }
          }
        }
        return param
      },
      getQueryParam (value) { // 获取查询字段参数 ٩(๑❛ᴗ❛๑)۶
        let model = this.searchModel
        let options = {}
        for (const key in model) {
          if (key !== 'checkInTime') {
            Object.assign(options, {[key]: model[key]})
          }
          delete model.currentPage
        }
        let time = {}
        if (Array.isArray(model.checkInTime) && model.checkInTime.length) {
          time = {
            startRegTime: formatTime(new Date(model.checkInTime[0])),
            endRegTime: formatTime(new Date(model.checkInTime[1]))
          }
        }
        let param = Object.assign({}, time, options, value)
        return this.filterNullFields(param)
      },
      getQueryParam2 (value) { // 获取查询字段参数 ٩(๑❛ᴗ❛๑)۶
        let model = this.searchModel2
        let options = {}
        for (const key in model) {
          if (key !== 'checkInTime') {
            Object.assign(options, {[key]: model[key]})
          }
          delete model.currentPage
        }
        let time = {}
        if (Array.isArray(model.checkInTime) && model.checkInTime.length) {
          time = {
            startTime: new Date(model.checkInTime[0]).getTime(),
            endTime: new Date(model.checkInTime[1]).getTime()
          }
        }
        let param = Object.assign({}, time, options, value)
        return this.filterNullFields(param)
      },
      // *********************************** 页面逻辑 *****************************************
      initPageData () {
        // 初始化页面数据 包括下拉菜单的选项以及表格数据
        // 这个参数拿的也太费劲了╭(╬◣д◢) 必须写在setTimeout里 否则娶不到model下的数据(╰_╯)#会报错
        setTimeout(() => {
          let initTableParm = {...{pageNum: 1, pageSize: 12}}
          Promise.all([this.getAllImageGroup(),this.getTableData(this.getQueryParam(initTableParm)),this.getTableData2(this.getQueryParam2(initTableParm)),this.getSystemImageGroup()]).then(res => {
          }).catch(err => {
            console.log('err', err)
          })
        })
      },
      getTableData (options) { // 获取表格初始数据 模拟请求回来的数据
        queryConditionList(options).then(res => { // 请求接口
          if (res.success) {
            let total = res.extra === undefined ? 0 : res.extra.total
            if (res.extra !==undefined && res.extra.total) { // 总数存在的话 加分页
              this.tableData.isPage = true
            } else {
              this.tableData.isPage = false
            }
            this.tableData.page = {
              currentPage: parseInt(this.searchModel.pageNum, 10),
              pagesize: this.searchModel.pageSize,
              handleSizeChange: this.handleSizeChange, // 分页条数改变触发该函数
              handleCurrentChange: this.handleCurrentChange, // 当前页码改变触发改函数
              Allpage: total
            }

            this.pageOptions.currentChageFlag = false // 防止点击分页条数时多次触发提交请求
            let content = res.data
            this.tableData.data = content
          }
        }).catch(err => {
          console.log('err', err)
        })
      },
      handleSizeChange (val) { // 分页条数改变触发该函数
        this.pageOptions.currentChageFlag = true
        let handlesize = this.getQueryParam({...{pageSize: val, pageNum: 1}})
        this.searchModel.pageNum = 1
        this.searchModel.pageSize = val
        this.getTableData(handlesize)
      },
      handleCurrentChange (val) { // 当前页码改变触发改函数
        if (!this.pageOptions.currentChageFlag) {
          const pagesize = this.tableData.page.pagesize
          let handlesize = this.getQueryParam({...{pageNum: val, pageSize: pagesize}})
          this.searchModel.pageNum = val
          this.searchModel.pageSize = pagesize
          this.getTableData(handlesize)
        }
      },
      getTableData2 (options) { // 获取表格初始数据 模拟请求回来的数据
        querySystemConditionList(options).then(res => { // 请求接口
          if (res.success) {
            let total = res.extra === undefined ? 0 : res.extra.total
            if (res.extra !== undefined && res.extra.total) { // 总数存在的话 加分页
              this.tableData2.isPage = true
            } else {
              this.tableData2.isPage = false
            }
            this.tableData2.page = {
              currentPage: parseInt(this.searchModel2.pageNum, 10),
              pagesize: this.searchModel2.pageSize,
              handleSizeChange: this.handleSizeChange2, // 分页条数改变触发该函数
              handleCurrentChange: this.handleCurrentChange2, // 当前页码改变触发改函数
              Allpage: total
            }

            this.pageOptions.currentChageFlag = false // 防止点击分页条数时多次触发提交请求
            let content = res.data
            this.tableData2.data = content
          }
        }).catch(err => {
          console.log('err', err)
        })
      },
      handleSizeChange2 (val) { // 分页条数改变触发该函数
        this.pageOptions.currentChageFlag = true
        let handlesize = this.getQueryParam2({...{pageSize: val, pageNum: 1}})
        this.searchModel2.pageNum = 1
        this.searchModel2.pageSize = val
        this.getTableData2(handlesize)
      },
      handleCurrentChange2 (val) { // 当前页码改变触发改函数
        if (!this.pageOptions.currentChageFlag) {
          const pagesize = this.tableData2.page.pagesize
          let handlesize = this.getQueryParam2({...{pageNum: val, pageSize: pagesize}})
          this.searchModel2.pageNum = val
          this.searchModel2.pageSize = pagesize
          this.getTableData2(handlesize)
        }
      },
      //系统分组
      getSystemImageGroup() {
        queryAllSystemGroup().then(res => { // 请求接口
          if (res.success) {
            this.allSystemImageGroup = this.typeList.concat(res.data)
            //this.groupList = res.data
          } else {
            alertError(res.msg,this)
          }
        }).catch(err => {
          console.log('err', err)
        })
      },
      changeType2(index){
        this.typeIndex2 = index
        let obj = this.allSystemImageGroup[index]
        if(obj.id === '-1') {
          this.searchModel2.groupId = ''
          this.searchModel2.isFull = 1
        } else if(obj.id === '0') {
          this.searchModel2.groupId = ''
          this.searchModel2.isFull = 0
        } else {
          this.searchModel2.groupId = obj.id
          this.searchModel2.isFull = 0
        }
        this.getTableData2(this.getQueryParam2({pageNum: 1, pageSize: 12}))
      },
      search2() {
        this.getTableData2(this.getQueryParam2({pageNum: 1, pageSize: 12}))
      },
      handleChange(file, fileList) {
        let image = file.raw
        let fileName = file.name
        let obj = {
          file:image,
          fileName:fileName
        }
        let array = []
        array.push(obj)
        let data = {
          files:array,
          groupId:this.searchModel.groupId
        }
        uploadImage(this.filterNullFields(data)).then(res => { // 请求接口
          if (res.success) {
            alertSuccess('添加图片成功',this)
            this.getTableData(this.getQueryParam({pageNum: 1, pageSize: 12}))
          } else {
            alertError(res.msg,this)
          }
        }).catch(err => {
          alertError('修改会员等级失败',this)
          console.log('err', err)
        })
      },
      getAllImageGroup() {
        queryAllImageGroup().then(res => { // 请求接口
          if (res.success) {
            this.allImageGroup = this.typeList.concat(res.data)
          } else {
            alertError(res.msg,this)
          }
        }).catch(err => {
          console.log('err', err)
        })
      },
      refreshImg() {
        this.getTableData(this.getQueryParam({pageNum: 1, pageSize: 12}))
        this.uploadImageVisible = false
      },
      closeDialog() {
        this.uploadImageVisible = false
      },
      openImgDialog() {
        this.uploadImageVisible = true
      },
      changeType(index){
        this.typeIndex = index
        let obj = this.allImageGroup[index]
        if(obj.id === '-1') {
          this.searchModel.groupId = ''
          this.searchModel.isFull = 1
        } else if(obj.id === '0') {
          this.searchModel.groupId = ''
          this.searchModel.isFull = 0
        } else {
          this.searchModel.groupId = obj.id
          this.searchModel.isFull = 0
        }
        this.getTableData(this.getQueryParam({pageNum: 1, pageSize: 12}))
      },
      chooseImg(id,index) {
        if(this.picId === id){
          this.picId = ''
        } else {
          this.picId = id
          this.imgIndex = index
        }
      },
      chooseOneImg(url) {
        if(this.imgList.indexOf(url) > -1){
          this.imgList.splice(this.imgList.indexOf(url),1)
        } else {
          this.imgList.push(url)
        }
      },
      confirmImg() {
        if(this.imgList.length > 0){
          this.$emit('imgUrl',this.imgList)
        } else {
          alertWarning('请选择图片',this)
        }
      },
      cancleImg() {
        this.chooseImage = ''
        this.$emit('close')
      },
      handleTagsClick(tab, event){
        if(tab.name === 'ONGOING'){
        } else if(tab.name === 'UNSTART'){
        }
      },
      search() {
        this.getTableData(this.getQueryParam({pageNum: 1, pageSize: 12}))
      },
    },
    mounted(){
      this.imgList = this.choosedImg
      this.initPageData()
    },
    computed:{},
    watch:{
      imgList(newValue, oldValue) {
        if(newValue.length > 8){
          this.imgList.splice((this.imgList.length - 1),1)
          alertWarning("最多只能选择8张图片！",this)
        }
      }
    },
  }
</script>
<style lang="scss">
  .ui-picture-search .el-input__icon{
    line-height: 30px !important;
  }
  .ui-picture-search .el-input__inner{
    padding-right: 2px !important;
    font-size: 12px !important;
  }
  .ui-pic-list .el-scrollbar{
    padding-bottom:0 !important;
  }
  .ui-tags .el-tabs__nav-wrap::after{
    background-color: transparent !important;
  }
  .ui-tags .el-tabs__nav-scroll{
    box-sizing: border-box;
    margin-top:0;
  }
  .ui-image-tabs .el-tabs__nav-scroll{
    margin-bottom:0 !important;
  }
  .ui-tags .el-tabs__item{
    height: 34px !important;
    line-height: 34px !important;
  }
  .ui-tags .el-tabs__active-bar{
    height: 4px !important;
  }
  .ui-tags .el-tabs__content{
    width:calc(100% + 30px);
    margin-left:-15px;
  }
  .ui-pic-item-list .el-radio-group{
    width:100%;
  }
</style>
<style scoped lang="scss">
  .ui-picture{
    width:calc(100% + 40px);
    margin-left:-20px;
    margin-top:-30px;
    margin-bottom: -30px;
    height:600px;
    .ui-picture-content{
      width:100%;
      height:550px;
      display: flex;
      border-top:1px solid #eee;
      .ui-picture-left{
        width:165px;
        height:100%;
        border-right: 1px solid #eee;
        padding:20px 15px;
        .ui-picture-search{
          height:30px;
        }
        .ui-picture-type{
          width:100%;
          height:calc(100% - 45px);
          .ui-group-item{
            width:100%;
            height:36px;
            border-radius: 10px;
            margin:1px 0;
            padding: 12px 20px;
            box-sizing: border-box;
            color: #B0AEB5;
            font-weight: bold;
            font-size: 12px;
            cursor: pointer;
          }
          .ui-choose-item{
            color: #35323b;
            background: #F2F2F6;
          }
          .ui-group-item:hover{
            color: #35323b;
            background: #F2F2F6;
          }
        }
      }
      .ui-picture-right{
        width:calc(100% - 165px);
        height:100%;
        .ui-search{
          display: flex;
          height:60px;
          padding:0 28px;
          margin-top:15px;
          .ui-search-display{
            display: flex;
            flex:1;
            .ui-search-name{
              height:28px;
              line-height: 28px;
              color: #595961;
              font-size:12px;
              margin-right:4px;
            }
            .ui-search-item{
              width:82px;
              height:28px;
              border-radius: 4px;
              text-align: center;
              line-height: 28px;
              color: #595961;
              font-size:12px;
              border: 1px solid #e3e2e5;
              margin-right:4px;
            }
            .ui-item-choose{
              background: #3f9eff !important;
              color:#fff !important;
            }
          }
        }
        .ui-pic-list{
          width:100%;
          height:380px;
          .ui-pic-item-list{
            padding:0 25px 20px 25px;
            box-sizing: border-box;
            overflow: hidden;
            .ui-pic-item-list-item{
              width:calc(25% - 19px);
              border:1px solid #eee;
              float:left;
              margin-right:19px;
              margin-bottom:20px;
              cursor: pointer;
              position: relative;
              .ui-pic-item-list-img{
                width:100%;
                height:100px;
                background-repeat: no-repeat;
                background-size: cover;
                background-position: center center;
                img{
                  width:100%;
                  height:100%;
                }
              }
              .ui-pic-item-list-text{
                width:100%;
                height:24px;
                line-height: 24px;
                display: block;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                margin-top: 5px;
                font-size: 12px;
                color: #595961;
                text-align: left;
                padding-left:8px;
                box-sizing: border-box;
              }
              .ui-pic-item-list-size{
                display: flex;
                padding:8px 13px;
                box-sizing: border-box;
                .ui-pic-item-list-size-filesize{
                  font-size:11px;
                  color:#999;
                  flex:1;
                  width:10px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
                .ui-pic-item-list-size-date{
                  font-size:11px;
                  color:#999;
                }
              }
              .ui-select-mask{
                border-radius: 6px;
                position: absolute;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                background: rgba(0, 0, 0, 0.5);
                text-align: center;
                img{
                  position: absolute;
                  top: 50px;
                  left: 45px;
                }
              }
            }
          }
        }
        .ui-pic-bottom{
          width:100%;
          height:50px;
          padding:11px 25px;
          display: flex;
          .ui-button{
            width:85px;
            height:28px;
            padding:0;
          }
          .ui-pagination{
            flex:1;
            text-align: right;
          }
        }
      }
    }
    .ui-picture-bottom{
      width:100%;
      height:50px;
      border-top:1px solid #eee;
      display: flex;
      align-items: center;
      justify-content: center;
      .ui-choose-info{
        color: #bbb !important;
        flex: 1;
        font-size:12px;
        box-sizing: border-box;
        span{
          padding:0 10px;
        }
      }
      .ui-choose-button{
        display: flex;
        align-items: center;
        justify-content: center;
        .ui-button{
          width:60px;
          height:30px;
          padding:0;
          margin-right:10px;
        }
      }
    }
  }
  .ui-tags{
    padding:0 15px;
    box-sizing: border-box;
  }
</style>
